package com.allenkerr.service.impl;

import com.allenkerr.mapper.RegionMapper;
import com.allenkerr.pojo.Region;
import com.allenkerr.pojo.RegionExample;
import com.allenkerr.service.RegionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by 小柯(Allen Kerr) on 17.5.15 10:18.
 */
@Service
public class RegionServiceImpl implements RegionService {

    @Autowired
    private RegionMapper regionMapper;

    private static final Logger LOGGER = LoggerFactory.getLogger(RegionServiceImpl.class);

    @Override
    public void saveOrUpdateBatch(List<Region> regionList) {
        for (Region region : regionList) {
            Region existedRegion = regionMapper.selectByPrimaryKey(region.getId());
            if (existedRegion != null && existedRegion.equals(region)) {
                LOGGER.info("{}与数据库已有数据相同，不做修改！", existedRegion);
            } else if (existedRegion != null && !existedRegion.equals(region)) {
                regionMapper.updateByPrimaryKeySelective(region);
                LOGGER.info("发现主键相同、内容不同的数据，执行修改操作，修改前：{}，修改后：{}。", existedRegion, region);
            } else {
                regionMapper.insertSelective(region);
                LOGGER.info("新添加数据{}。", region);
            }
        }
    }

    @Override
    public void updateRegion(String id, String province, String city) {
        Region region = regionMapper.selectByPrimaryKey(id);
        if (region == null) {
            return;
        }
        if (province != null) {
            region.setProvince(province);
        }
        if (city != null) {
            region.setCity(city);
        }
        regionMapper.updateByPrimaryKeySelective(region);
    }

    @Override
    public List<Region> findAll() {
        RegionExample example = new RegionExample();
        List<Region> regionList = regionMapper.selectByExample(example);
        return regionList;
    }

}
